package com.douziit.meilianoa.base.utils;



import com.douziit.meilianoa.base.exception.TipException;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017/11/13
 */
public class TokenUtil {

    public  static  String userTokenMangerKey(Integer uid){
        return  "userIdManger_"+uid;
    }

    private static final String UND = "_";

    public static String getKey(String prefix, String... keys) {
        String suffix = "";
        if (keys != null) {
            suffix = StrUtil.join(keys, UND);
        }
        return prefix.concat(suffix);
    }

    public static String hash(String str) {
        return sha1(str).toString();
    }

    public static String generator(String... strs) {
        return generator(Arrays.asList(strs));
    }

    public static String generator(List<String> strList) {
        Collections.sort(strList);
        String strs = StrUtil.join(strList.toArray(), "");
        byte[] bytes = sha1(strs).toString().getBytes();
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * sha1 安全加密算法
     *
     * @param decrypt 签名摘要
     * @return
     */
    private static String sha1(String decrypt) {
        //获取信息摘要 - 参数字典排序后字符串
        try {
            //指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            //获取字节数组
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new TipException("签名错误!", e);
        }
    }
}
